package com.quanyan.club.mq.consumer;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.club.mq.constant.MqConstant;
import com.quanyan.club.service.ClubMemberService;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.user.mq.UserUpdateNotifyMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * 用户中心通知，如果有昵称改变或者电话号码改变
 */
@Component
public class UserCenterUpdateConsumer extends AbstractMqConsumer {

    private static final Logger log = LoggerFactory.getLogger(UserCenterUpdateConsumer.class);

    @Autowired
    private ClubMemberService clubMemberService;

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        MessageExt messageExt = messages.get(0);
        String msgId = messageExt.getKeys();
        byte[] bodyByte = messageExt.getBody();

        try {
            UserUpdateNotifyMsg notifyMsg = (UserUpdateNotifyMsg) ObjectUtil.toObject(bodyByte);
            int type = notifyMsg.getUpdateType();
            if (type == MqConstants.UserUpdateType.NICKNAME_UPDATE){
                clubMemberService.updateClubMemberIndex(notifyMsg.getUid());
            }
        }catch (Exception e){
            e.printStackTrace();
            log.warn("收到用户中心更新用户信息，执行出错");
        }

        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    @PostConstruct
    void run() {
        log.warn("nameServerAddress : " + nameServerAddress + ", 监听用户信息更新consumer启动成功");
        super.start();
    }

    @Override
    protected String getConsumerGroup() {
        return MqConstant.USERINFO_UPDATE_FROM_USER_CENTER_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return MqConstant.USERINFO_UPDATE_FROM_USER_CENTER_INSTANCE;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(
                MqConstants.UserUpdateTopicAndTags.USER_UPDATE_NOTIFY_TOPIC, MqConstants.UserUpdateTopicAndTags.USER_UPDATE_NOTIFY_TAGS);
        return mqTopics;
    }
}
